const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// 确保 temp 目录存在
const tempDir = path.join(__dirname, '../../temp');
if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
}

class DifyService {
    constructor() {
        // 从环境变量获取配置
        this.baseURL = process.env.DIFY_BASE_URL || 'http://localhost/v1';
        this.apiKey = process.env.DIFY_API_KEY;

        // 验证必要的配置
        if (!this.apiKey) {
            throw new Error('Dify API key not configured');
        }
    }

    static getInstance() {
        if (!DifyService.instance) {
            DifyService.instance = new DifyService();
        }
        return DifyService.instance;
    }

    async getResponse(message, conversationId, userId, onProgress) {
        try {
            console.log('开始调用Dify服务...', {
                conversationId,
                userId,
                message
            });
            
            const response = await fetch(`${this.baseURL}/chat-messages`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.apiKey}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    inputs: {},
                    query: message,
                    response_mode: "streaming",
                    conversation_id: conversationId || "", // 使用传入的会话ID
                    user: userId // 使用传入的用户ID
                })
            });

            if (!response.ok) {
                throw new Error(`Dify API 错误: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullResponse = '';
            let currentMessageId = '';
            let newConversationId = ''; // 用于存储新的 conversation_id
            let metadata = null;

            while (true) {
                const { value, done } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n\n');

                for (const line of lines) {
                    if (line.trim().startsWith('data: ')) {
                        try {
                            onProgress && onProgress(line + '\n\n');
                            const data = JSON.parse(line.slice(6));
                            
                            switch (data.event) {
                                case 'agent_message':
                                    currentMessageId = data.message_id;
                                    newConversationId = data.conversation_id; // 保存新的 conversation_id
                                    if (data.answer) {
                                        fullResponse += data.answer;
                                    }
                                    break;
                                case 'message_end':
                                    metadata = data.metadata;
                                    break;
                                case 'error':
                                    throw new Error(data.message || '未知错误');
                            }
                        } catch (e) {
                            console.error('解析SSE数据错误:', e);
                        }
                    }
                }
            }

            return {
                content: fullResponse,
                role: 'assistant',
                messageId: currentMessageId,
                conversationId: newConversationId, // 返回新的 conversation_id
                metadata: metadata
            };
        } catch (error) {
            console.error('Dify服务错误:', error);
            throw error;
        }
    }

    async getResponseWithImage(message, imageUrl, sessionMessages = [], onProgress) {
        try {
            console.log('开始调用Dify图片服务...');
            
            // 从数据库会话中获取 conversation_id
            const conversationId = sessionMessages.length > 0 
                ? sessionMessages[0].conversation_id 
                : "";

            // 使用固定格式的用户ID
            const userId = sessionMessages.length > 0 
                ? sessionMessages[0].user_id 
                : `user-${Date.now()}`;

            console.log('发送图片请求到Dify:', {
                userId,
                conversationId,
                message,
                imageUrl
            });

            const response = await fetch(`${this.baseURL}/chat-messages`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.apiKey}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    inputs: {},
                    query: message,
                    response_mode: "streaming",
                    conversation_id: conversationId,
                    user: userId,
                    files: [{
                        type: "image",
                        transfer_method: "remote_url",
                        url: imageUrl
                    }]
                })
            });

            if (!response.ok) {
                throw new Error(`Dify API 错误: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullResponse = '';
            let currentMessageId = '';
            let metadata = null;

            while (true) {
                const { value, done } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n\n');

                for (const line of lines) {
                    if (line.trim().startsWith('data: ')) {
                        try {
                            onProgress && onProgress(line + '\n\n');

                            const data = JSON.parse(line.slice(6));
                            
                            switch (data.event) {
                                case 'message':
                                    currentMessageId = data.message_id;
                                    if (data.answer) {
                                        fullResponse += data.answer;
                                    }
                                    break;
                                case 'message_end':
                                    metadata = data.metadata;
                                    console.log('对话完成，元数据:', metadata);
                                    break;
                                case 'error':
                                    throw new Error(data.message || '未知错误');
                            }
                        } catch (e) {
                            console.error('解析SSE数据错误:', e);
                        }
                    }
                }
            }

            return {
                content: fullResponse,
                role: 'assistant',
                messageId: currentMessageId,
                conversationId: conversationId,
                metadata: metadata
            };
        } catch (error) {
            console.error('Dify图片处理错误:', error);
            throw error;
        }
    }

    async uploadFile(file, userId) {
        let tempFilePath = null;
        try {
            console.log('开始上传文件到Dify...', {
                fileName: file.originalname,
                userId,
                mimetype: file.mimetype
            });

            // 生成唯一的临时文件名
            const timestamp = Date.now();
            const uniqueFileName = `${timestamp}-${file.originalname}`;
            tempFilePath = path.join(tempDir, uniqueFileName);

            // 写入临时文件
            await fs.promises.writeFile(tempFilePath, file.buffer);
            console.log('临时文件已创建:', tempFilePath);

            const form = new FormData();
            form.append('file', fs.createReadStream(tempFilePath));
            form.append('user', `user-${userId}`);

            const response = await axios.post(`${this.baseURL}/files/upload`, form, {
                headers: {
                    'Authorization': `Bearer ${this.apiKey}`,
                    ...form.getHeaders()
                }
            });

            console.log('文件上传成功:', response.data);
            return response.data;
        } catch (error) {
            console.error('文件上传失败:', error);
            throw error;
        } finally {
            // 清理临时文件
            if (tempFilePath && fs.existsSync(tempFilePath)) {
                try {
                    await fs.promises.unlink(tempFilePath);
                    console.log('临时文件已删除:', tempFilePath);
                } catch (err) {
                    console.error('删除临时文件失败:', err);
                }
            }
        }
    }

    async getResponseWithLocalFile(message, file, conversationId, userId, onProgress) {
        try {
            // 先上传文件
            const uploadResult = await this.uploadFile(file, userId);

            console.log('开始调用Dify图片服务...', {
                conversationId,
                userId,
                message,
                fileId: uploadResult.id
            });

            const response = await fetch(`${this.baseURL}/chat-messages`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.apiKey}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    inputs: {},
                    query: message,
                    response_mode: "streaming",
                    conversation_id: conversationId || "",
                    user: `user-${userId}`,
                    files: [{
                        type: "image",
                        transfer_method: "local_file",
                        upload_file_id: uploadResult.id
                    }]
                })
            });

            if (!response.ok) {
                throw new Error(`Dify API 错误: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullResponse = '';
            let currentMessageId = '';
            let newConversationId = '';
            let metadata = null;

            while (true) {
                const { value, done } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n\n');

                for (const line of lines) {
                    if (line.trim().startsWith('data: ')) {
                        try {
                            onProgress && onProgress(line + '\n\n');

                            const data = JSON.parse(line.slice(6));
                            
                            switch (data.event) {
                                case 'agent_message':
                                    currentMessageId = data.message_id;
                                    newConversationId = data.conversation_id;
                                    if (data.answer) {
                                        fullResponse += data.answer;
                                    }
                                    break;
                                case 'message_end':
                                    metadata = data.metadata;
                                    break;
                                case 'error':
                                    throw new Error(data.message || '未知错误');
                            }
                        } catch (e) {
                            console.error('解析SSE数据错误:', e);
                        }
                    }
                }
            }

            return {
                content: fullResponse,
                role: 'assistant',
                messageId: currentMessageId,
                conversationId: newConversationId,
                metadata: metadata
            };
        } catch (error) {
            console.error('Dify本地文件处理错误:', error);
            throw error;
        }
    }
}

module.exports = DifyService.getInstance();